<?php

namespace Home\Controller;

use Think\Controller;
// 引入我们的主项目的入口类。
use EasyWeChat\Foundation\Application;

class CommonController extends Controller
{
    var $product;
    var $category;
    var $gallery;
    var $customer;
    var $cart;
    var $order;
    var $order_product;
    var $address;

    public function __construct()
    {
        parent::__construct();

        $this->product = M('Product');
        $this->category = M('Category');
        $this->gallery = M('Gallery');
        $this->customer = M('Customer');
        $this->cart = M('Cart');
        $this->order = M('Orders');
        $this->order_product = M('Order_product');
        $this->address = M('Address');

        $this->check_login();
        //登录成功之后跳回当前页面
        $_SESSION['url'] = $_SERVER['REQUEST_URI'];
//        dump($_SESSION['url']);exit;
    }

    /**
     * 检查用户是否登录
     */
    function check_login()
    {
        //微信接口
//        $app = new Application(C('options'));
//        $oauth = $app->oauth;
//        // 未登录
//        if (empty($_SESSION['wechat_user'])) {
////            $_SESSION['target_url'] = '/';  //可以省略
//            $oauth->redirect()->send();
//        }

        //统计购物车数量,判断购物车有没有商品，有就显示没有就隐藏
        $customer_id = $_SESSION['customer']['id'];
        if ($customer_id) {
            $this->count_carts = $this->cart->where("customer_id = '$customer_id'")->sum('num');
        }
    }


    /**
     * 回掉方法
     */
    public function oauth_callback()
    {
        $app = new Application(C('options'));
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $_SESSION['wechat_user'] = $user->toArray();
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
        header('location:' . $targetUrl); // 跳转到 user/profile
    }

}